import java.awt.BorderLayout;
import java.awt.EventQueue;

import javax.swing.*;
import javax.swing.border.EmptyBorder;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;



public class AuctionUI extends JFrame {

	private JPanel contentPane;
	private Player p[];
	private JLabel blockName;
	private JButton doneButton;
	private JButton bidButton[];
	private Block propertyToBeAuctioned;
	private Block nextPropertyToBeAuctioned;
	private Block[] propertiesToBeAuctioned;
	private PropertyBlock[] propBlock;
	private PropertyBlock[] ownedPropBlock;
	private Utilities[] utilBlock;
	private Utilities[] ownedUtilBlock;
	private RailRoad[] railBlock;
	private RailRoad[] ownedRailBlock;
	private int numOfPropertiesToBeAuctioned=0;
	private Utilities utility;
	private RailRoad railroad;
	private AuctionComponentUI[] component;
	private AuctionComponentUI highestBidder = null;
	private int lastButtonPressed;

	private int highestBid = -1;
	
	
	/**
	 * Create the frame.
	 */
	public AuctionUI(Block propertyToBeAuctioned,Player p[]) {
		
		this.propertyToBeAuctioned = propertyToBeAuctioned;
		
		
		this.p = p;
		
		this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		this.setBounds(100, 100, 450, 374);
		this.contentPane = new JPanel();
		this.contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
		this.setContentPane(this.contentPane);
		this.contentPane.setLayout(null);
		this.setVisible(true);
		
		this.component = new AuctionComponentUI[8];
		
		if(this.propertyToBeAuctioned instanceof PropertyBlock){
		
			this.blockName = new JLabel("Auction for: " +((PropertyBlock) this.propertyToBeAuctioned).getPropertyName());
		
		}else if(this.propertyToBeAuctioned instanceof RailRoad){
			
			this.blockName = new JLabel("Auction for: " +((RailRoad) this.propertyToBeAuctioned).getName());
			
		}else if(this.propertyToBeAuctioned instanceof Utilities){
			
			this.blockName = new JLabel("Auction for: " +((Utilities) this.propertyToBeAuctioned).getName());
			
		}
		
		
		this.doneButton = new JButton("Done");
		this.bidButton = new JButton[p.length];
		
		this.contentPane.add(this.blockName);
		this.contentPane.add(this.doneButton);
		this.doneButton.setBounds(296, 23, 100, 50);
		this.blockName.setBounds(25, 41, 265, 14);
		
		
		this.setComponents();
		this.setButton();
		
		this.doneButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
            	
            	if(highestBid != -1){
            		
            		setOwnerofAuctionedProperty();
            		
            	}else{JOptionPane.showMessageDialog(null, "Nag-Error: Wala pang tumatawad");}
            	
            }
        });
	
	}
	
	public AuctionUI(Block[] propertiesToBeAuctioned,Player p[],Player play) {
		int tempPropCount = 0;
		int tempRailCount = 0;
		int tempUtilCount = 0;
		
		int totalProp = 0;
		int totalRail = 0;
		int totalUtil = 0;
		Player cPlayer = play;
		
		Block[] tempBlock = propertiesToBeAuctioned;
		this.propBlock = new PropertyBlock[22];
		this.utilBlock = new Utilities[2];
		this.railBlock = new RailRoad[4];
		
		for(int i=0; i<tempBlock.length; i++){
			if(tempBlock[i] instanceof PropertyBlock){
				propBlock[totalProp]=(PropertyBlock)tempBlock[i];
				totalProp++;
			}else if(tempBlock[i] instanceof Utilities){
				utilBlock[totalUtil]=(Utilities)tempBlock[i];
				totalUtil++;
			}else if(tempBlock[i] instanceof RailRoad){
				railBlock[totalRail]=(RailRoad)tempBlock[i];
				totalRail++;
			}
		}
		
		
		for(int i=0; i<propBlock.length; i++){
			if(propBlock[i].getCOwner()== cPlayer){
				tempPropCount++;
			}
		}
		
		for(int i=0; i<utilBlock.length; i++){
			if(utilBlock[i].getCOwner()== cPlayer){
				tempUtilCount++;
			}
		}
		
		for(int i=0; i<railBlock.length; i++){
			if(railBlock[i].getCOwner()== cPlayer){
				tempRailCount++;
			}
		}
		
		this.ownedPropBlock= new PropertyBlock[tempPropCount];
		this.ownedUtilBlock= new Utilities[tempUtilCount];
		this.ownedRailBlock= new RailRoad[tempRailCount];
		this.propertiesToBeAuctioned= new Block[tempPropCount+tempRailCount+tempUtilCount];
		
		int tempOwnedBlockCount = 0;
		int tempOwnedPropCount = 0;
		int tempOwnedUtilCount = 0;
		int tempOwnedRailCount = 0;
		
		for(int i=0; i<propBlock.length; i++){
			if(propBlock[i].getCOwner()== cPlayer){
				this.ownedPropBlock[tempOwnedPropCount]=propBlock[i];
				this.propertiesToBeAuctioned[tempOwnedBlockCount]=(Block)ownedPropBlock[tempOwnedPropCount];
				tempOwnedPropCount++;
				tempOwnedBlockCount++;
			}
		}
		
		for(int i=0; i<utilBlock.length; i++){
			if(utilBlock[i].getCOwner()== cPlayer){
				this.ownedUtilBlock[tempOwnedUtilCount]=utilBlock[i];
				this.propertiesToBeAuctioned[tempOwnedBlockCount]=(Block)ownedUtilBlock[tempOwnedUtilCount];
				tempOwnedUtilCount++;
				tempOwnedBlockCount++;
			}
		}
		
		for(int i=0; i<railBlock.length; i++){
			if(railBlock[i].getCOwner()== cPlayer){
				this.ownedRailBlock[tempOwnedRailCount]=railBlock[i];
				this.propertiesToBeAuctioned[tempOwnedBlockCount]=(Block)ownedRailBlock[tempOwnedRailCount];
				tempOwnedRailCount++;
				tempOwnedBlockCount++;
			}
		}
		
		this.numOfPropertiesToBeAuctioned=this.propertiesToBeAuctioned.length-1;
		
		if(this.numOfPropertiesToBeAuctioned>=0){
			this.nextPropertyToBeAuctioned=this.propertiesToBeAuctioned[this.numOfPropertiesToBeAuctioned];
			
			this.p = p;
			
			this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
			this.setBounds(100, 100, 450, 374);
			this.contentPane = new JPanel();
			this.contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
			this.setContentPane(this.contentPane);
			this.contentPane.setLayout(null);
			this.setVisible(true);
			
			
			
			multipleAuctionsProtocol();
			System.out.println("made it into multiple auctions");
		}else{
			Command cmd = new NextPlayerCommand();
			cmd.execute();
			this.dispose();
		}
		
	}

	public void multipleAuctionsProtocol(){
		this.component = new AuctionComponentUI[8];
		
		if(this.nextPropertyToBeAuctioned instanceof PropertyBlock){
		
			this.blockName = new JLabel("Auction for: " +((PropertyBlock) this.nextPropertyToBeAuctioned).getPropertyName());
		
		}else if(this.nextPropertyToBeAuctioned instanceof RailRoad){
			
			this.blockName = new JLabel("Auction for: " +((RailRoad) this.nextPropertyToBeAuctioned).getName());
			
		}else if(this.nextPropertyToBeAuctioned instanceof Utilities){
			
			this.blockName = new JLabel("Auction for: " +((Utilities) this.nextPropertyToBeAuctioned).getName());
			
		}
		
		
		this.doneButton = new JButton("Done");
		this.bidButton = new JButton[this.p.length];
		System.out.println(bidButton.length+"hi hi");
		this.contentPane.add(this.blockName);
		this.contentPane.add(this.doneButton);
		this.doneButton.setBounds(296, 23, 100, 50);
		this.blockName.setBounds(25, 41, 265, 14);
		
		
		this.setComponents();
		this.setButton();
		
		this.doneButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
            	
            	if(highestBid != -1){
            		
            		setOwnerofAuctionedProperty();
            		
            	}else{JOptionPane.showMessageDialog(null, "Nag-Error: Wala pang tumatawad");}
            	
            }
        });

	}
	
	private void setComponents(){
		int tempCount=0;
		for(int counter = 0, yAxis = 84; counter<this.p.length; counter++){
			
			if(this.p[counter].getActive()==true){
				component[tempCount] = new AuctionComponentUI(this.p[counter].getPlayerName());
				this.bidButton[tempCount] = new JButton("Bid");
				this.contentPane.add(component[tempCount].getPlayerNameLabel());
				this.contentPane.add(component[tempCount].getBidTextField());
				this.contentPane.add(bidButton[tempCount]);
				
				component[tempCount].getPlayerNameLabel().setBounds(80, yAxis-16, 120, 50);
				component[tempCount].getBidTextField().setBounds(150, yAxis, 100, 20);
				bidButton[tempCount].setBounds(260, yAxis, 70, 20);
				
				yAxis = yAxis + 30;
				
				component[tempCount].setComponentOwner(this.p[counter]);
				tempCount++;
			}
		}
		
	}
	
	private void setButton(){
		int tempCounter = 0;
		for(int i=0; i<p.length;i++){
			if(this.p[i].getActive()==true){
				tempCounter++;
			}
		}
		
		bidButton[0].addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
            	lastButtonPressed = 0;
            	bidButtonProtocol();
            }
        });
		if(tempCounter-1 == 0)
			return;
		bidButton[1].addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
            	lastButtonPressed = 1;
            	bidButtonProtocol();
            }
        });
		if(tempCounter-1 == 1)
			return;
		bidButton[2].addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
            	lastButtonPressed = 2;
            	bidButtonProtocol();
            	
            }
        });
		if(tempCounter-1 == 2)
			return;
		bidButton[3].addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
            	lastButtonPressed = 3;
            	bidButtonProtocol();
            }
        });
		if(tempCounter-1 == 3)
			return;
		bidButton[4].addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
            	lastButtonPressed = 4;
            	bidButtonProtocol();
            }
        });
		if(tempCounter-1 == 4)
			return;
		bidButton[5].addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
            	lastButtonPressed = 5;
            	bidButtonProtocol();
            }
        });
		if(tempCounter-1 == 5)
			return;
		bidButton[6].addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
            	lastButtonPressed = 6;
            	bidButtonProtocol();
            }
        });
		if(tempCounter-1 == 6)
			return;
		bidButton[7].addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
            	lastButtonPressed = 7;
            	bidButtonProtocol();
            }
        });
		if(tempCounter-1 == 7)
			return;
	}
	
	public void removeComponents(){
		this.contentPane.remove(blockName);
		int tempCount = 0;
		for(int i=0; i<this.component.length; i++){
			if(this.component[i]!=null){
				tempCount++;
			}
		}
		
		for(int i=0; i<tempCount;i++){
			this.contentPane.remove(this.component[i].getPlayerNameLabel());
			this.contentPane.remove(this.component[i].getBidTextField());
			this.contentPane.remove(this.bidButton[i]);
		}
		
		this.bidButton=null;
		this.blockName=null;
		this.component=null;
	}
	
	private void bidButtonProtocol(){
		
		if(this.isTextFieldFilled()){
		
			if(this.isHighestBid()){
				
				if(this.isCapableOfPaying()){
					
					if(this.highestBidder != null){
						
						this.highestBidder.getBidTextField().setEnabled(true);
						this.setHighestBidButtonToFalse();
						
						
					}
					
					this.bidButton[this.lastButtonPressed].setEnabled(false);
					this.highestBidder = component[this.lastButtonPressed];
					this.highestBid = Integer.parseInt(this.highestBidder.getBidTextField().getText());
					this.highestBidder.getBidTextField().setEnabled(false);
						
					
				}else{JOptionPane.showMessageDialog(null, "Nag-Error: Hindi abot ng pera mo ang iyong tawad");}
				
			}else{JOptionPane.showMessageDialog(null, "Nag-Error: Ang iyong tawad ay mas mababa sa pinakamataas na tawad");}
		
		}else{JOptionPane.showMessageDialog(null, "Nag-Error: Walang nakalagay na tawad");}
	}
	//checkers
	
	private boolean isHighestBid(){
		
		boolean returnValue = true;
		try{
		if(Integer.parseInt(component[this.lastButtonPressed].getBidTextField().getText()) <= this.highestBid)
			returnValue = false;
		}catch(Exception e){JOptionPane.showMessageDialog(null, "Nag-Error: Hindi pwede ang nilagay mong tawad.");}
		
		return returnValue;
	}
	
	private boolean isTextFieldFilled(){
		
		boolean returnValue = true;
		
		if(component[this.lastButtonPressed].getBidTextField().getText().isEmpty())
			returnValue = false;
			
		
		return returnValue;
		
	}
	
	private boolean isCapableOfPaying(){
		
		boolean returnValue = true;
		try{
		if(Integer.parseInt(component[this.lastButtonPressed].getBidTextField().getText()) > component[this.lastButtonPressed].getComponentOwner().getCurrentMoney())
			returnValue = false;
		}catch(Exception e){JOptionPane.showMessageDialog(null, "Nag-Error: Hindi pwede ang nilagay mong tawad.");}
		
		return returnValue;
		
	}
	
	//end of checkers
	
	private void setHighestBidButtonToFalse(){
		int tempPlayerCount = 0;
		for(int i=0; i<p.length; i++){
			if(this.p[i].getActive()==true){
				tempPlayerCount++;
			}
		}
		
		for(int counter = 0; counter<tempPlayerCount; counter++){
			
			if(!this.bidButton[counter].isEnabled())
				this.bidButton[counter].setEnabled(true);
			
		}
		
	}
	
	private void setOwnerofAuctionedProperty(){
		
		if(this.propertyToBeAuctioned!=null){
			if(this.propertyToBeAuctioned instanceof PropertyBlock){
				
				((PropertyBlock) this.propertyToBeAuctioned).setCOwner(this.highestBidder.getComponentOwner());
				
			}else if(this.propertyToBeAuctioned instanceof RailRoad){
				
				((RailRoad) this.propertyToBeAuctioned).setCOwner(this.highestBidder.getComponentOwner());
				
			}else if(this.propertyToBeAuctioned instanceof Utilities){
				
				((Utilities) this.propertyToBeAuctioned).setCOwner(this.highestBidder.getComponentOwner());
				
			}
			
			this.highestBidder.getComponentOwner().subtractMoney(Integer.parseInt(this.highestBidder.getBidTextField().getText()));
			
			Command cmd = new NextPlayerCommand();
			cmd.execute();
			
			this.dispose();
		}else{
			if(this.numOfPropertiesToBeAuctioned>0){
				this.nextPropertyToBeAuctioned=this.propertiesToBeAuctioned[this.numOfPropertiesToBeAuctioned];
				
				if(this.nextPropertyToBeAuctioned instanceof PropertyBlock){
					
					((PropertyBlock) this.nextPropertyToBeAuctioned).setCOwner(this.highestBidder.getComponentOwner());
					((PropertyBlock) this.nextPropertyToBeAuctioned).setCurrentNumberOfHouses(0);
					
				}else if(this.nextPropertyToBeAuctioned instanceof RailRoad){
					
					((RailRoad) this.nextPropertyToBeAuctioned).setCOwner(this.highestBidder.getComponentOwner());
					
				}else if(this.nextPropertyToBeAuctioned instanceof Utilities){
					
					((Utilities) this.nextPropertyToBeAuctioned).setCOwner(this.highestBidder.getComponentOwner());
					
				}
				
				this.highestBidder.getComponentOwner().subtractMoney(Integer.parseInt(this.highestBidder.getBidTextField().getText()));
				this.numOfPropertiesToBeAuctioned--;
				this.nextPropertyToBeAuctioned=this.propertiesToBeAuctioned[this.numOfPropertiesToBeAuctioned];
				
				this.highestBid=-1;
				this.removeComponents();
				this.multipleAuctionsProtocol();
				
			}else{
				this.nextPropertyToBeAuctioned=this.propertiesToBeAuctioned[this.numOfPropertiesToBeAuctioned];
				
				if(this.nextPropertyToBeAuctioned instanceof PropertyBlock){
					
					((PropertyBlock) this.nextPropertyToBeAuctioned).setCOwner(this.highestBidder.getComponentOwner());
					
				}else if(this.nextPropertyToBeAuctioned instanceof RailRoad){
					
					((RailRoad) this.nextPropertyToBeAuctioned).setCOwner(this.highestBidder.getComponentOwner());
					
				}else if(this.nextPropertyToBeAuctioned instanceof Utilities){
					
					((Utilities) this.nextPropertyToBeAuctioned).setCOwner(this.highestBidder.getComponentOwner());
					
				}
				
				this.highestBidder.getComponentOwner().subtractMoney(Integer.parseInt(this.highestBidder.getBidTextField().getText()));
				
				Command cmd = new NextPlayerCommand();
				cmd.execute();
				
				this.dispose();
			}
		}
	}
	
}
